package com.aind.common.utils.reflect;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by lpeng on 2017/2/27.
 */
public class ReflectUtil {
    private static Logger logger = Logger.getLogger(ReflectUtil.class);
    private ReflectUtil(){}

    /**
     * 获得声明属性
     * @param obj
     * @param fieldName
     * @return
     */
    public static Field getFile(Object obj, String fieldName){
        Field field = null;
        for (Class c = obj.getClass(); c != Object.class; c = c.getSuperclass()){
            try {
                field = c.getDeclaredField(fieldName);
                return field;
            } catch (NoSuchFieldException e) {
            }
        }
        return field;
    }

    /**
     * 获取属性值
     * @param obj
     * @param fieldName
     * @return
     * @throws IllegalAccessException
     */
    public static Object getFileValue(Object obj, String fieldName) throws IllegalAccessException {
        Object value = null;
        Field field = ReflectUtil.getFile(obj, fieldName);
        if (null != field){
            if (field.isAccessible()){
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);

            }
        }
        return  value;
    }

    /**
     * 设置属性值
     * @param obj   要设置的对象
     * @param fieldName 要设置的属性名
     * @param value
     */
    public static void setFileValue(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        if(obj instanceof Map) {
            Map field = (Map)obj;
            field.put(fieldName, value);
        } else {
            Field field1 = obj.getClass().getDeclaredField(fieldName);
            if(field1.isAccessible()) {
                field1.set(obj, value);
            } else {
                field1.setAccessible(true);
                field1.set(obj, value);
                field1.setAccessible(false);
            }
        }
    }
}
